/**
 * 泛娱区块链 - Mine
 * @zaric
 * 设置
 */

'use strict';

import React from 'react'
import {StyleSheet, View} from 'react-native'
import {ListRow} from 'teaset'
import NavigationBar from '../../component/navigation/NavigationBar'
import Button from '../../component/common/Button';
import JShareModule from 'jshare-react-native';
import {inject, observer} from 'mobx-react';

@inject('loginStore')
@observer
class Settings extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            dataSource: [
                // { key: 'pull', title: '推送管理' },
                {key: 'password', title: '修改密码', detail: null},
                {key: 'wechat', title: '绑定微信', detail: '未绑定'},
                {key: 'qq', title: '绑定QQ', detail: '未绑定'},
                {key: 'clear', title: '清理缓存', detail: null},
            ],
            isLogIn: global.secretKey
        }
    }

    componentDidMount() {
        this.requestDataSources();
    }

    componentWillMount() {
    }

    requestDataSources = async () => {
        let {getUserData, getUserInfo} = this.props.loginStore;
        let result = await getUserData(getUserInfo.user_id);
        if (result.code === StatusCode.SUCCESS_CODE) {
            let dataSourceTemp = this.state.dataSource;
            dataSourceTemp[1].detail = result.data.wx_token ? '已绑定' : '未绑定';
            dataSourceTemp[2].detail = result.data.qq_token ? '已绑定' : '未绑定';
            this.setState({
                dataSource: dataSourceTemp,
            });
        }
    };

    onPressAuthorize = (platform) => {
        let {userInfo} = this.props.loginStore;
        JShareModule.authorize({platform}, async (map) => {
            //绑定微信
            let url = ServicesApi.BIND_PLATFORM;
            let data = {};
            if (platform === 'qq') {
                let authData = {
                    access_token: map.token,
                    unionid: 1,
                };
                // let url = `${ServicesApi.GET_AUTH_QQ}?access_token=${map.token}&unionid=1`;
                let result = await Services.get(ServicesApi.GET_AUTH_QQ, authData, {type: 'qq_login'});
                let formatAuth = result.substring(10, result.length - 3);
                // console.log('formatAuth',formatAuth);
                data = {
                    type: 'qq_bind',
                    qq_token: JSON.parse(formatAuth).unionid,
                }
            } else {
                data = {
                    type: 'wx_bind',
                    wx_token: JSON.parse(map.originData).unionid,
                }
            }
            data = {
                ...data,
                user_id: userInfo.user_id
            };
            this.onSubmitBindRequest(url, data);
        }, (errorCode) => {
            // console.log('errorCode', errorCode);
            let {error_message} = errorCode.description;
            ToastManager.show(error_message);
        });
    };

    onSubmitBindRequest = async (url, data) => {
        // console.log('userData---->', data);
        let result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.requestDataSources();
            ToastManager.show('绑定成功');
        } else {
            ToastManager.show(result.msg);
        }
    };

    _onPressItem = ({key, detail}) => {
        let {loginStore} = this.props;
        switch (key) {
            case 'pull':
                break;
            case 'password':
                RouterHelper.navigate('修改密码', 'ChangePwd', {page_flag: 'change'});
                break;
            case 'wechat':
                detail === '未绑定' && this.onPressAuthorize('wechat');
                break;
            case 'qq':
                detail === '未绑定' && this.onPressAuthorize('qq');
                break;
            case 'clear':
                let params = {
                    title: '温馨提示',
                    detail: '确定要清除缓存？',
                    actions: [
                        {
                            title: '取消', onPress: () => {
                            }
                        },
                        {
                            title: '确定', onPress: () => {
                                ToastManager.show('清除成功!')
                            }
                        }
                    ]
                };
                AlertManager.show(params);
                break;
            default:
                break;
        }
    };

    _onPressLogout = () => {
        let {loginStore} = this.props;
        let params = {
            title: '温馨提示',
            detail: '确定要注销登录？',
            actions: [
                {
                    title: '取消', onPress: () => {
                    }
                },
                {
                    title: '确定', onPress: () => {
                        ToastManager.show('退出成功!');
                        loginStore.cleanUserInfo();
                        this.setState({isLogIn: true});
                        RouterHelper.reset('', 'Login');
                    }
                }
            ]
        };
        AlertManager.show(params)
    };

    requestAuthorize = async (params) => {
        // console.log(map)
        let {loginStore} = this.props;
        let result = await loginStore.gotoLogin(ServicesApi.USER_LOGIN, params);
        if (result.code === 0) {
            ActionsManager.show({
                actions: [
                    {
                        title: '绑定当前账号',
                        onPress: () => {
                            RouterHelper.navigate('', 'BindingPhone')
                        }
                    },
                ]
            })
        }
    };

    renderContent = (dataSource) => {
        let content = dataSource.map((item, index) => {
            return (
                <ListRow
                    key={`${index}`}
                    onPress={() => this._onPressItem(item)}
                    accessory={'auto'}
                    style={styles.listRow}
                    icon={item.icon}
                    detail={item.detail}
                    title={item.title}
                />
            )
        });
        return content;
    };

    render() {
        let {isLogIn, dataSource} = this.state;
        return (
            <View style={styles.container}>
                <NavigationBar
                    title={'设置'}
                />
                {this.renderContent(dataSource)}
                {isLogIn && <Button style={styles.button} title={'注销登录'} onPress={this._onPressLogout}/>}

            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    listRow: {
        paddingLeft: 15,
        paddingRight: 15,
        paddingTop: 13,
        paddingBottom: 13,
    },
    button: {
        marginTop: 25,
        marginHorizontal: 30,
        backgroundColor: Theme.themeColor,
        color: '#fff'
    },

});
export default Settings